package hongcaosp.app.android.user.settings.share;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blackchopper.loginshare.impl.LoginShare;
import com.blackchopper.loginshare.interfaces.OnLoginshareListener;
import com.blackchopper.loginshare.model.Type;
import com.blackchopper.loginshare.model.WechatMessageBody;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.tencent.liteav.demo.common.utils.FileUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.login.UserToken;
import hongcaosp.app.android.modle.bean.UserInfo;
import hongcaosp.app.android.user.qrcode.QRCodeUtil;
import hongcaosp.app.android.user.qrcode.QRUserBean;
import hongcaosp.app.android.user.settings.SettingsActivity;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.DensityUtils;
import xlj.lib.android.base.utils.DialogUtil;
import xlj.lib.android.base.utils.JsonUtil;
import xlj.lib.android.base.utils.ScreenUtils;

/**
 * 分享我的个人主页
 */
public class DialogShareHome extends Dialog implements OnLoginshareListener {

    private View shareView;
    private File sharePic;

    private LoginShare loginShare;
    public DialogShareHome(@NonNull Context context, AppCompatActivity activity) {
        super(context);
        loginShare = new LoginShare(activity);
        loginShare.register(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setGravity(Gravity.CENTER);
        getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);

        setContentView(R.layout.dialog_share_home);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                loginShare.unRegister();
            }
        });
        UserInfo userInfo = UserToken.getDefault().getUser();

        shareView = findViewById(R.id.rl_share_view);
        final ImageView qrCodeIV = findViewById(R.id.qrcode_iv);
        TextView nickTV = findViewById(R.id.nick);
        nickTV.setText(userInfo.getNickName());
        QRUserBean userBean = new QRUserBean();
        userBean.setUserId(userInfo.getId());
        userBean.setNickName(userInfo.getNickName());
        final String content = JsonUtil.toJsonStr(userBean);
        Glide.with(getContext()).load(userInfo.getImage()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                int size = ScreenUtils.getScreenWidth(getContext()) - DensityUtils.dip2px(getContext(),200);
                Bitmap bitmap = QRCodeUtil.createQRCodeWithLogo(content,size,resource);
                qrCodeIV.setImageBitmap(bitmap);
            }
        });

        findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        findViewById(R.id.btn_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AndPermission.with(getContext())
                        .runtime()
                        .permission(Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                        .onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                view2Pic();
                            }
                        })
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                ToastManager.getInstance().showToast("请给予我读写权限");
                            }
                        })
                        .start();

            }
        });
    }

    @Override
    public void onLoginSuccess(Type type, String code, String info) {

    }

    @Override
    public void onLoginCancel(Type type) {

    }

    @Override
    public void onLoginError(Type type, int errorCode) {

    }

    @Override
    public void onShareSuccess(Type type) {
        if (sharePic != null && sharePic.exists()) {
            sharePic.delete();
        }
        ToastManager.getInstance().showToast("分享成功");
    }

    @Override
    public void onShareCancel(Type type) {
        if (sharePic != null && sharePic.exists()) {
            sharePic.delete();
        }
        ToastManager.getInstance().showToast("分享取消");
    }

    @Override
    public void onShareError(Type type, int code) {
        if (sharePic != null && sharePic.exists()) {
            sharePic.delete();
        }
        ToastManager.getInstance().showToast("分享失败");
    }

    private void view2Pic() {

        int w = shareView.getWidth();
        int h = shareView.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bmp);
        canvas.drawColor(Color.WHITE);

        shareView.layout(0, 0, w, h);
        shareView.draw(canvas);

        try {
            sharePic = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.jpg");
            if (sharePic.exists()) {
                sharePic.delete();
            }
            FileOutputStream fos = new FileOutputStream(sharePic);
            bmp.compress(Bitmap.CompressFormat.JPEG,100,fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            sharePic.delete();
        }

        if (!sharePic.exists()) {
            ToastManager.getInstance().showToast("分享失败");
            return;
        }
        WechatMessageBody wechatMessageBody = new WechatMessageBody();
        wechatMessageBody.type = WechatMessageBody.TIMELINE;
        wechatMessageBody.msgType = WechatMessageBody.MSG_IMAGE;
        wechatMessageBody.setLocalImage(sharePic.getAbsolutePath());
        wechatMessageBody.title("红草视频");
        loginShare.launchWechatShare(wechatMessageBody);
    }
}
